import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined, ExperimentOutlined, CopyOutlined, ApartmentOutlined,
  UserOutlined, SearchOutlined, EllipsisOutlined, MenuOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker, Popconfirm, Tree, Input, Row, Col, Card, Divider, Dropdown, Menu, Tabs } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'
import useStore from '../../useStore.js'
import { clearCache, useDidCache, useDidRecover, dropByCacheKey } from 'react-router-cache-route';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'
var storage = window.localStorage;
const { Option } = Select;
const { Search } = Input;
import Sortable from '../newmes/sortable.js';
import { use_bgcd_initcolmun } from './use_sys_config.js';

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

// 初始化表格列配置
const initColumns = use_bgcd_initcolmun()

const Bgcd_list = () => {
  const history = useHistory();
  const [selectedRows, setSelectedRows] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [treeData, setTreeData] = useState([])
  const [tableData, setTableData] = useState([])
  const [allMenuData, setAllMenuData] = useState([])
  const [selectedTreeNode, setSelectedTreeNode] = useState({
    key: '/shipSRM',
    title: '盛世前程人力资源共享平台',
    level: 0
  })
  const [expandedKeys, setExpandedKeys] = useState([])
  const [autoExpandParent, setAutoExpandParent] = useState(true)
  const [searchValue, setSearchValue] = useState('')
  const [isTableSettingModalOpen, setIsTableSettingModalOpen] = useState(false) // 表格设置模态框
  const [columnarr, setColumnarr] = useState(initColumns)
  const [initSize, setInitSize] = useState(1)
  const [ifshow, setIfshow] = useState(true)
  
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  useEffect(() => {
    queryTreeData()
    storage['Pc_bgcd_list'] ? setColumnarr(JSON.parse(storage['Pc_bgcd_list'])) : setColumnarr(initColumns)
    storage['Pc_bgcd_list_initsize'] ? setInitSize(storage['Pc_bgcd_list_initsize']) : setInitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setIfshow(true) }, [ifshow])

  // 路由跳转
  const tonormal = (route) => {
    history.push({ pathname: route });
  }

  // 查询菜单树形数据
  const queryTreeData = async () => {
    setIsLoading(true)
    try {
      let rtdata = await fetchsync_util("/admin/sys/bgcdlb", 'POST', {}, "json")
      
      // 处理时间格式
      rtdata.resultdata.forEach(element => {
        element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
        element.update_time = convertISODateTimeToYYYYMMDDHHMMSS(element.update_time)
      });

      const processedData = dealnullorundenfined(rtdata.resultdata)
      setAllMenuData(processedData)
      console.log('所有菜单数据:', processedData.length, '条')
      console.log('一级菜单数据:', processedData.filter(menu => menu.jjcd === '1').length, '条')
      
      // 设置初始表格数据为所有一级菜单
      const firstLevelMenus = processedData.filter(menu => menu.jjcd === '1')
      setTableData(firstLevelMenus)
      setSelectedRowKeys([])
      setSelectedRows([])
      
      // 构建树形结构
      const treeDataFromApi = buildMenuTree(processedData)

      console.log(treeDataFromApi,"T---R---E---E---D---A---T---A---")
      setTreeData(treeDataFromApi)
      
      // 默认展开根节点
      setExpandedKeys(['/shipSRM'])
      
      console.log('初始化完成，显示', firstLevelMenus.length, '条一级菜单')
    } catch (error) {
      console.error('查询菜单失败:', error);
      openNotification_util('查询菜单失败，请稍后重试');
    }
    setIsLoading(false)
  }

  // 构建菜单树形结构
  const buildMenuTree = (menuData) => {
    // 创建根节点
    const rootNode = {
      title: '盛世前程人力资源共享平台',
      key: '/shipSRM',
      lycd: '/shipSRM',
      level: 0,
      data: null, // 根节点不需要具体的菜单数据
      children: []
    }

    // 按级别分组菜单
    const menuByLevel = {}
    menuData.forEach(menu => {
      const level = menu.jjcd || 1
      if (!menuByLevel[level]) {
        menuByLevel[level] = []
      }
      menuByLevel[level].push(menu)
    })

    // 构建一级菜单
    const firstLevelMenus = menuByLevel[1] || []
    firstLevelMenus.forEach(menu => {
      const menuNode = {
        title: menu.cdmc,
        key: menu.cdly,
        lycd: menu.cdly,
        level: 1,
        data: menu,
        children: []
      }
      
      // 查找二级菜单
      const secondLevelMenus = (menuByLevel[2] || []).filter(subMenu => 
        subMenu.parent_mc === menu.cdmc
      )
      
      secondLevelMenus.forEach(subMenu => {
        const subMenuNode = {
          title: subMenu.cdmc,
          key: subMenu.cdly,
          lycd: subMenu.cdly,
          level: 2,
          data: subMenu,
          children: []
        }
        
        // 查找三级菜单
        const thirdLevelMenus = (menuByLevel[3] || []).filter(thirdMenu => 
          thirdMenu.parent_mc === subMenu.cdmc
        )
        
        thirdLevelMenus.forEach(thirdMenu => {
          const thirdMenuNode = {
            title: thirdMenu.cdmc,
            key: thirdMenu.cdly,
            lycd: thirdMenu.cdly,
            level: 3,
            data: thirdMenu
          }
          subMenuNode.children.push(thirdMenuNode)
        })
        
        menuNode.children.push(subMenuNode)
      })
      
      rootNode.children.push(menuNode)
    })

    return [rootNode]
  }

  // 查询表格数据 - 根据菜单路由三级关系进行逐级查询
  const queryTableData = (nodeKey) => {
    setIsLoading(true)
    try {
      let filteredData = []

      if (nodeKey === '/shipSRM') {
        // 根节点，显示所有一级菜单
        filteredData = allMenuData.filter(menu => menu.jjcd === '1')
      } else {
        // 通过菜单路由逐级查找子菜单
        // 先找到当前节点
        const selectedMenu = allMenuData.find(menu => menu.cdly === nodeKey)
        if (selectedMenu) {
          const currentLevel = selectedMenu.jjcd || 1
          // 只查找直接下一级的菜单（即三级关系中的下一级）
          filteredData = allMenuData.filter(menu => {
            // 路由逐级关系：父节点的cdly是当前节点的cdly
            // 子节点的cdly以当前节点cdly为前缀，并且级别是当前级别+1
            // 例如：/shipSRM/a  -> /shipSRM/a/b
            return (
              menu.cdly !== selectedMenu.cdly &&
              menu.cdly.startsWith(selectedMenu.cdly.endsWith('/') ? selectedMenu.cdly : selectedMenu.cdly + '/') &&
              (menu.jjcd || 1) === currentLevel + 1
            )
          })
        }
      }

      setTableData(filteredData)
      setSelectedRowKeys([])
      setSelectedRows([])
    } catch (error) {
      console.error('查询表格数据失败:', error);
      openNotification_util('查询表格数据失败');
    }
    setIsLoading(false)
  }

  // 树节点选择
 
  // 点击树的某个节点后，表格显示该节点及该节点所有子节点
  // 树节点选择
  // 需求：如果选中的是根节点（key为/shipSRM），则显示所有一级菜单（/shipSRM/xxx），
  // 如果选中的是一级菜单节点（如/shipSRM/zbzx），则显示所有以该节点key为前缀的菜单（/shipSRM/zbzx/xxx）
  const onTreeSelect = (selectedKeys, info) => {
    if (selectedKeys.length > 0) {
      setSelectedTreeNode(info.node);
      const nodeKey = selectedKeys[0];
      setIsLoading(true);
      try {
        let filteredData = [];
       if (nodeKey === '/shipSRM') {
          // 根节点，显示所有一级菜单（级别为1的菜单）
          filteredData = allMenuData.filter(menu => {
            return menu.jjcd === '1';
          });
                      // console.log('根节点查询结果:', filteredData.length, '条一级菜单');
        } else if (
          nodeKey.startsWith('/shipSRM/') &&
          nodeKey.split('/').length === 3
        ) {
          // 选中的是一级菜单节点（如/shipSRM/zbzx），显示所有以该key为前缀的菜单（不包括自己）
          filteredData = allMenuData.filter(menu => {
            return (
              menu.cdly &&
              menu.cdly.startsWith(nodeKey + '/') // 只要是该一级菜单下的子菜单
            );
          });
          // console.log(`一级菜单 ${nodeKey} 查询结果:`, filteredData.length, '条子菜单');
        } else {
          // 其他情况，默认显示当前节点及其所有子节点（递归）
          const selectedMenu = allMenuData.find(menu => menu.id && menu.id.toString() === nodeKey);
          if (selectedMenu) {
            // 获取当前节点的菜单名称
            const currentCdmc = selectedMenu.cdmc;
            // 获取当前节点的菜单级别
            const currentJjcd = selectedMenu.jjcd;
            // 递归查找所有子节点
            const getAllChildren = (parentCdmc, parentJjcd) => {
              let children = allMenuData.filter(menu => menu.parent_mc === parentCdmc && menu.jjcd === parentJjcd + 1);
              let all = [...children];
              children.forEach(child => {
                all = all.concat(getAllChildren(child.cdmc, child.jjcd || (parentJjcd + 1)));
              });
              return all;
            };
            // 当前节点及其所有子节点
            filteredData = [
              selectedMenu,
              ...getAllChildren(currentCdmc, currentJjcd)
            ];
          }
        }
        setTableData(filteredData);
        setSelectedRowKeys([]);
        setSelectedRows([]);
      } catch (error) {
        console.error('查询表格数据失败:', error);
        openNotification_util('查询表格数据失败');
      }
      setIsLoading(false);
    }
  }

  // 树节点展开
  const onTreeExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  // 搜索树节点
  const onTreeSearch = (value) => {
    setSearchValue(value)
    if (value) {
      const expandedKeys = getExpandedKeys(treeData, value)
      setExpandedKeys(expandedKeys)
      setAutoExpandParent(true)
    }
  }

  // 获取展开的节点keys
  const getExpandedKeys = (data, searchValue) => {
    const expandedKeys = []
    const loop = (data) => {
      data.forEach(item => {
        if (item.title.indexOf(searchValue) > -1) {
          expandedKeys.push(item.key)
        }
        if (item.children) {
          loop(item.children)
        }
      })
    }
    loop(data)
    return expandedKeys
  }

  // 高亮搜索文本
  const getTreeTitle = (title) => {
    if (searchValue && title.indexOf(searchValue) > -1) {
      const index = title.indexOf(searchValue)
      const beforeStr = title.substr(0, index)
      const afterStr = title.substr(index + searchValue.length)
      return (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      )
    }
    return title
  }

  // 递归处理树数据添加高亮
  const processTreeData = (data) => {
    return data.map(item => ({
      ...item,
      title: getTreeTitle(item.title),
      children: item.children ? processTreeData(item.children) : []
    }))
  }

  // 手动刷新
  const handleRefresh = () => {
    queryTreeData()
  }

  // 新增菜单
  const handleAdd = async () => {
    storage.pre_bgcd_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey("bgmenu_form")
    setnowroute({...{route:"/shipSRM/sys/bgmenu_form",title:"菜单配置_新增"}})
  }

  // 编辑菜单
  const handleEdit = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
    }
    else {
      storage.pre_bgcd_item = JSON.stringify({ data: selectedRows[0], type: "edit" })
      dropByCacheKey("bgmenu_form")
      setnowroute({...{route:"/shipSRM/sys/bgmenu_form",title:"菜单配置_编辑"}})
    }
  }

  // 复制菜单
  const handleCopy = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
    }
    else {
      storage.pre_bgcd_item = JSON.stringify({ data: selectedRows[0], type: "copy" })
      dropByCacheKey("bgmenu_form")
      setnowroute({...{route:"/shipSRM/sys/bgmenu_form",title:"菜单配置_复制"}})
    }
  }

  // 删除菜单
  const handleDelete = async () => {
    let rtdata = await fetchsync_util("/admin/sys/delete_bgcd", 'POST', { selectedRows }, "json")
    rtdata.rtstatus ? queryTreeData() : 1
  }

  // 导出
  const handleExport = () => {
    useexcelauto(selectedRows.length > 0 ? selectedRows : tableData, columnarr, '菜单配置')
  }

  // 跳转到角色管理
  const handleJumpToRole = () => {
    dropByCacheKey("js_list")
    setnowroute({...{route:"/shipSRM/sys/js_list",title:"业务角色"}})
  }



  // 添加子菜单
  const handleAddSubMenu = (nodeData) => {
    storage.pre_bgcd_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey("bgmenu_form")
    setnowroute({...{route:"/shipSRM/sys/bgmenu_form",title:"菜单配置_新增"}})
  }

  // 编辑菜单名称
  const handleRename = (nodeData) => {
    if (nodeData.key === '/shipSRM') {
      openNotification_util("根节点不能编辑")
      return
    }
    
    storage.pre_bgcd_item = JSON.stringify({ data: nodeData.data, type: "edit" })
    dropByCacheKey("bgmenu_form")
    setnowroute({...{route:"/shipSRM/sys/bgmenu_form",title:"菜单配置_编辑"}})
  }

  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <Row gutter={16} style={{ height: '100%' }}>
          {/* 左侧菜单树形区域 */}
          <Col span={6} style={{ height: '100%', borderRight: '1px solid #f0f0f0' }}>
            <Card 
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <MenuOutlined style={{ marginRight: 8 }} />
                  系统菜单结构
                </div>
              }
              size="small" 
              style={{ height: '100%' }}
              bodyStyle={{ height: 'calc(100% - 57px)', overflow: 'auto', padding: '8px' }}
            >
              <Search
                style={{ marginBottom: 8 }}
                placeholder="搜索菜单"
                onSearch={onTreeSearch}
                allowClear
              />
              {isLoading ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Spin />
                </div>
              ) : (
                <Tree
                  showLine
                  showIcon
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent} 
                  selectedKeys={selectedTreeNode ? [selectedTreeNode.key] : []}
                  onExpand={onTreeExpand}
                  onSelect={onTreeSelect}
                  treeData={processTreeData(treeData)}
                  titleRender={(nodeData) => {
                    const isSelected = selectedTreeNode?.key === nodeData.key;
                    return (
                      <div 
                        style={{ 
                          display: 'flex',
                          alignItems: 'center', 
                          width: '100%',
                          padding: '4px 8px',
                          borderRadius: '4px',
                          backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                          transition: 'all 0.3s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = '#f5f5f5';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'visible';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = isSelected ? '#e6f7ff' : 'transparent';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'hidden';
                        }}
                      >
                        <span style={{ flex: 1 }}>
                          {nodeData.title}
                        </span>
                        <div className="node-action-button" style={{visibility: 'hidden'}}>
                          <Dropdown
                            trigger={['click']}
                            menu={{
                              items: [
                                {
                                  key: '1',
                                  label: '添加子菜单',
                                  icon: <PlusSquareOutlined />,
                                  onClick: () => handleAddSubMenu(nodeData)
                                },
                                ...(nodeData.key !== '/shipSRM' ? [{
                                  key: '2',
                                  label: '编辑菜单', 
                                  icon: <EditOutlined />,
                                  onClick: () => handleRename(nodeData)
                                }] : [])
                              ]
                            }}
                          >
                            <Button
                              type="text" 
                              size="small"
                              icon={<EllipsisOutlined />}
                              onClick={e => e.stopPropagation()}
                            />
                          </Dropdown>
                        </div>
                      </div>
                    );
                  }}
                />
              )}
            </Card>
          </Col>

          {/* 右侧菜单管理区域 */}
          <Col span={18} style={{ height: '100%' }}>
            <Card 
              title={
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>
                    <ProfileOutlined style={{ marginRight: 8 }} />
                    {selectedTreeNode ? `${selectedTreeNode.title} - 子菜单管理` : '菜单管理'}
                  </span>
                  <div style={{ display: 'flex', gap: '8px' }}>
                    <Button size="small" onClick={handleRefresh}>
                      <ReloadOutlined />刷新
                    </Button>
                    <Button size="small" onClick={handleExport}>
                      <FileExcelOutlined />导出
                    </Button>
                  </div>
                </div>
              }
              style={{ height: '100%' }} 
              bodyStyle={{ height: 'calc(100% - 57px)', padding: '8px' }}
            >
              {/* 操作按钮区域 */}
              <div style={{ marginBottom: '14px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                <Button 
                  style={{ backgroundColor: "white", color: "#004C8B", fontWeight: "800" }}
                  onClick={handleAdd}
                >
                  <PlusSquareOutlined />新增菜单
                </Button>
                <Button 
                  style={{ backgroundColor: "white", color: "#004C8B", fontWeight: "800" }}
                  onClick={handleEdit}
                >
                  <EditOutlined />编辑菜单
                </Button>
                <Button 
                  style={{ backgroundColor: "#004C8B", color: "white", fontWeight: "800" }}
                  onClick={handleCopy}
                >
                  <CopyOutlined />复制菜单
                </Button>
                <Popconfirm title="确定删除吗?" onConfirm={handleDelete}>
                  <Button style={{ backgroundColor: "white", color: "#004C8B", fontWeight: "800" }}>
                    <MinusSquareOutlined />删除菜单
                  </Button>
                </Popconfirm>
                <Button 
                  style={{ backgroundColor: "#004C8B", color: "white", fontWeight: "800" }}
                  onClick={handleJumpToRole}
                >
                  <UserOutlined />跳转角色
                </Button>
              </div>

              {/* 表格设置按钮 */}
              <div style={{ position: 'relative' }}>
                <IconFont 
                  type="setting" 
                  style={{ position: 'absolute', right: '2vw', top: '-3rem', fontSize: "1.5rem", zIndex: 10 }}
                  onClick={() => setIsTableSettingModalOpen(true)} 
                />
                {ifshow && (
                  <Sortable 
                    tableColnum={columnarr} 
                    handleTableColomn={(data) => { setColumnarr(data); }}
                    storageName={"Pc_bgcd_list"} 
                    open={isTableSettingModalOpen} 
                    handleOpen={(data) => { setIsTableSettingModalOpen(data); }}
                    initSize={initSize} 
                    handleInitSize={(data) => { setInitSize(data); storage['Pc_bgcd_list_initsize'] = data; }}
                  />
                )}
              </div>

              {/* 表格区域 */}
              {isLoading ? (
                <div style={{ textAlign: 'center', padding: '50px' }}>
                  <Spin />
                </div>
              ) : (
                <Custom_table_hooks_config 
                  tabledata={tableData} 
                  tablecolnum={columnarr}
                  width="100%"
                  sfdoubleclick="false" 
                  ifhiddencchangeselecttype="true"
                  selectedRows={selectedRows} 
                  selectedRowKeys={selectedRowKeys}
                  defaultPageSize={20}
                  bordered
                  scroll={{ y: 'calc(100vh - 400px)', x: initSize * 1250 }}
                  handleselectson={(selectedRows, selectedRowKeys) => {
                    setSelectedRows(selectedRows)
                    setSelectedRowKeys(selectedRowKeys)
                  }}
                />
              )}
            </Card>
          </Col>
        </Row>


      </div>
    </div>
  )
}

export default Bgcd_list

const styles = {
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
    padding: "14px"
  }
}